import socket
from .SysUtil import platform


def net_message(data=None):
    host = 'localhost'
    port = 2048
    if platform() == 'win32':
        host = '192.168.43.1'
    if data is None:
        data = {
            'type': 0,
            'payload': {
                'id': 0,
                'data': {'msg': '远方发来消息'}
            },
            'result': 0,
        }
    s = socket.socket()
    try:
        s.connect((host, port))
        s.send((str(data) + '\n').encode())

        if data.get('result') == 0:
            return '0'

        data = s.recv(1024).decode()
        if data == '-1':
            return None

        return data
    except(ConnectionRefusedError, ConnectionResetError, Exception):
        print('辅助服务未启动')

    return 'control fail'


def sendMessage(_type, _id, data, need_result):
    _data = {
        'type': _type,
        'payload': {
            'id': _id,
            'data': data
        },
        'result': need_result,
    }
    return net_message(_data)


def sendAppMsg(_id, data, need_result=0):
    return sendMessage(0, _id, data, need_result)


# 辅助功能通道
def sendACMsg(_id, data, need_result=0):
    return sendMessage(1, _id, data, need_result)


def sendACId(_id):
    return sendACMsg(_id, '')



